import { useState, useRef, useEffect } from 'react'
import { motion } from 'framer-motion'
import { AuthService } from '../api/auth';
import { AxiosManager } from '../utils/axiosInstance'; // 移除未使用的 isResponseSuccess
import type { Variants } from 'framer-motion';
// 添加LocationService导入
import { LocationService } from '../api/location';
// 在导入部分添加Link
import { Link } from 'react-router-dom';

interface LoginFormProps {
  onLoginSuccess?: () => void
}

const LoginForm = ({ onLoginSuccess }: LoginFormProps) => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const formRef = useRef<HTMLDivElement>(null)

  // 表单元素动画变体
  const formVariants: Variants = {
    hidden: { opacity: 0, y: 20 },
    visible: (i: number) => ({
      opacity: 1,
      y: 0,
      transition: {
        delay: 0.3 + i * 0.1,
        duration: 0.6,
        ease: "easeOut"
      }
    })
  }

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsSubmitting(true);
  
    // 表单验证
    if (!username || !password) {
      setError('请输入用户名和密码');
      setIsSubmitting(false);
      return;
    }
  
    try {
      // 调用登录API
      const result = await AuthService.login({ username, password });
      
      console.log('登录结果:', result);
      
      // 保存令牌后立即检查认证状态
      const token = localStorage.getItem('Authorization');
      console.log('本地存储中的令牌:', token);
      console.log('当前认证状态:', AxiosManager.isAuthenticated());
  
      // 增强的成功判断逻辑
      const loginSuccess = result && (
        // 检查常见的成功状态码格式
        (typeof result.code === 'string' && (result.code === '0' || result.code === '200')) ||
        // 直接检查认证状态（如果令牌已保存）
        AxiosManager.isAuthenticated()
      );
      
      console.log('登录成功判断结果:', loginSuccess);
      
      if (loginSuccess) {
        // 登录成功处理
        console.log('登录成功，准备调用onLoginSuccess回调');
        // 使用setTimeout确保令牌完全保存
        setTimeout(async () => {
          try {
            console.log('开始获取并发送位置信息...');
            // 获取当前位置并发送到服务器
            await LocationService.getCurrentLocationAndSend();
            console.log('位置信息获取和发送成功');
          } catch (locationError) {
            console.warn('位置信息获取失败，但不影响登录流程:', locationError);
            // 使用备用方案：发送模拟位置数据
            try {
              const mockLocationData = {
                latitude: 39.9042,
                longitude: 116.4074,
                accuracy: 85.5,
                timestamp: new Date().toISOString()
              };
              await LocationService.sendLocationToServer(mockLocationData);
              console.log('备用位置数据发送成功');
            } catch (mockError) {
              console.error('备用位置数据发送失败:', mockError);
            }
          } finally {
            // 无论位置信息是否成功发送，都执行登录成功回调
            if (typeof onLoginSuccess === 'function') {
              console.log('执行onLoginSuccess回调');
              onLoginSuccess();
            } else {
              console.log('onLoginSuccess不存在');
              alert(result.msg || '登录成功！');
            }
          }
        }, 200); // 增加延迟以确保认证信息完全保存
      } else {
        // 登录失败处理
        setError(result.msg || '登录失败，请检查您的用户名和密码');
      }
    } catch (err) {
      console.error('登录错误:', err);
      setError('登录过程中发生错误，请稍后再试');
    } finally {
      // 无论成功失败，都要重置提交状态
      setIsSubmitting(false);
    }
  };

  // 点击外部关闭错误提示
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (formRef.current && !formRef.current.contains(event.target as Node) && error) {
        setError('');
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [error]);

  return (
    <motion.div 
      className="w-full max-w-md bg-white dark:bg-white/5 backdrop-blur p-8 md:p-10 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700"
      ref={formRef}
      whileHover={{ boxShadow: '0 25px 50px -12px rgba(99, 102, 241, 0.25)' }}
      transition={{ duration: 0.3 }}
    >
      {/* 登录图标 */}
      <motion.div 
        className="flex justify-center mb-6"
        initial={{ scale: 0, rotate: -180 }}
        animate={{ scale: 1, rotate: 0 }}
        transition={{ duration: 0.8, type: "spring", bounce: 0.3 }}
      >
        <div className="w-16 h-16 rounded-full bg-gradient-primary flex items-center justify-center text-white text-2xl shadow-glow">
          🔐
        </div>
      </motion.div>
      
      <motion.h2 
        className="text-3xl font-bold text-center mb-2 text-primary dark:text-primary text-shadow"
        custom={0}
        initial="hidden"
        animate="visible"
        variants={formVariants}
      >
        欢迎回来
      </motion.h2>
      
      <motion.p 
        className="text-center text-gray-500 dark:text-gray-400 mb-8"
        custom={1}
        initial="hidden"
        animate="visible"
        variants={formVariants}
      >
        请登录您的账号继续访问
      </motion.p>
      
      {error && (
        <motion.div 
          className="bg-danger/10 text-danger p-3 text-sm rounded-lg mb-6 border border-danger/30"
          initial={{ height: 0, opacity: 0, marginBottom: 0 }}
          animate={{ height: 'auto', opacity: 1, marginBottom: 24 }}
          exit={{ height: 0, opacity: 0, marginBottom: 0 }}
          transition={{ duration: 0.3 }}
        >
          <div className="flex items-start">
            <span className="mr-2 text-lg">⚠️</span>
            <span>{error}</span>
          </div>
        </motion.div>
      )}
      
      <form onSubmit={handleLogin} className="space-y-6">
        <motion.div 
          custom={2}
          initial="hidden"
          animate="visible"
          variants={formVariants}
        >
          <label 
            htmlFor="username" 
            className="block mb-2 text-sm font-medium text-gray-700 dark:text-gray-300"
          >
            用户名
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="请输入用户名"
              disabled={isSubmitting}
              className="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300"
              autoComplete="username"
            />
          </div>
        </motion.div>
        
        <motion.div 
          custom={3}
          initial="hidden"
          animate="visible"
          variants={formVariants}
        >
          <div className="flex justify-between items-center mb-2">
            <label 
              htmlFor="password" 
              className="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              密码
            </label>
            <a href="#" className="text-xs text-primary hover:text-primary/80 transition-colors">
              忘记密码？
            </a>
          </div>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>
            <input
              type={showPassword ? "text" : "password"}
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入密码"
              disabled={isSubmitting}
              className="w-full pl-10 pr-10 py-3 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300"
              autoComplete="current-password"
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              disabled={isSubmitting}
            >
              {showPassword ? (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M6.632 19.171L12 13.8V19c0 .556-.444 1-1 1h-4c-.556 0-1-.444-1-1v-1.338m0 0L9.878 9.878m-3.29 3.29a3 3 0 104.243-4.243m4.242 4.242L15.12 9.88m-4.242 0L9.88 15.12"
                  />
                </svg>
              ) : (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"
                  />
                </svg>
              )}
            </button>
          </div>
        </motion.div>
        
        <motion.button 
          type="submit" 
          disabled={isSubmitting}
          className="w-full py-3 bg-gradient-primary border-none rounded-lg text-white font-medium hover:shadow-glow transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:shadow-none"
          whileHover={!isSubmitting ? { scale: 1.02 } : {}}
          whileTap={!isSubmitting ? { scale: 0.98 } : {}}
          custom={4}
          initial="hidden"
          animate="visible"
          variants={formVariants}
        >
          {isSubmitting ? (
            <div className="flex items-center justify-center space-x-2">
              <svg className="animate-spin -ml-1 mr-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span>登录中...</span>
            </div>
          ) : (
            '登录'
          )}
        </motion.button>
      </form>

      <motion.div 
        className="mt-6 text-center"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.8, delay: 0.9 }}
      >
        <p className="text-gray-600 dark:text-gray-300 text-sm">
          没有账号？ <Link to="/register" className="text-primary hover:text-primary-dark font-medium">立即注册</Link>
        </p>
      </motion.div>
    </motion.div>
  )
}
export default LoginForm
